<?php
/**
 * 邮件批量投递
 *
 * @author     Akon(番茄红了) <aultoale@gmail.com>
 */
class CLI_Edm extends CLI
{

    public function main()
    {
        $config = Kohana::config('mail');

        // 取出商户会员
        $select = DB::select('email', 'nickname')
            ->from('members')
            ->where('member_type', '=', 2);

        // 实例化迭代器
        $iterator = new Db_Iterator($select, 'default', 10);

        Vendor::register_autoloader('Zend');

        // 循环取出数据
        while ($iterator->valid())
        {
            // 遍历数据
            foreach ($iterator->current() as $row)
            {
                // 实例化邮件发送器
                $transport = new Zend_Mail_Transport_Smtp($config->host, $config->options);

                // 实例化 Zend_Mail
                $zendMail = new Zend_Mail('utf-8');
                $mailSubject = '华强北在线盛大开幕，商家订单包邮发补贴';
                $mailContent = file_get_contents(DOCROOT.'/web/mail/freeexpress.html');

                try
                {
                    // 发送邮件
                    $zendMail->addTo($row['email'], $row['nickname'])
                        ->setFrom('servers@360hqb.com', '华强北在线')
                        ->setSubject($mailSubject)
                        ->setBodyHtml($mailContent)
                        ->send($transport);

                    CLI::output("id: ".$row['email']." 发送成功 √ \n");

                    // 每次发送，休息10秒钟
                    sleep(5);
                }
                catch (Exception $e)
                {
                    CLI::output("id: ".$row['email']." 发送失败 × \n");
                }
            }
            $iterator->next();
        }
    }
}